/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { useState, useEffect } from 'react';
import { Form, Input, message, Select, Descriptions, Radio, Typography } from 'antd';
import { sendCode } from '@/services/Finance/transfer';
import {
  cdFinanceAccount,
  cdFinanceOperateAccount,
  cdOperateReasonList,
  getUserTypeMap,
} from '@/services/Finance/jdkTransfer';
import type { Options } from '../type';
import { operateOptions, accountOptions, modifyMoneyOptions, FormColFormat } from '../index.config';
import type { AccountInfo } from '../index.config';
import KbCaptcha from '@/components/KbCaptcha/';
import Button from 'antd/es/button';
import { debounce } from 'lodash';

const FormItem = Form.Item;
const { Title } = Typography;
const Index = () => {
  const [phone, setPhone] = useState<string>('');
  const [balance, setBalance] = useState<{ avail_money: string; cash_money: string }>();
  const [modifyMoney, setModifyMoney] = useState<string>('plus');
  const [accountInfo, setAccountInfo] = useState<AccountInfo>();
  const [options, setOptions] = useState<Options[]>([]);
  const [userType, setUserType] = useState<Options[]>([]);
  const [form1] = Form.useForm();
  const [form2] = Form.useForm();
  const kb_type_Value = Form.useWatch('kb_type', form1);
  const operateValue = Form.useWatch('operate', form2);

  const handlemodifyMoney = (event: any) => {
    const { value } = event.target || {};
    setModifyMoney(value);
  };
  const changePhone = (event: any) => {
    const { value } = event.target || {};
    setPhone(value);
  };
  const onCheck = () => form2.validateFields(['phone']);
  const handleSearch = (values: AccountInfo) => {
    const { username, kb_type } = values;
    setAccountInfo({ username, kbType: kb_type });
    cdFinanceAccount(values).then((res) => {
      const { code, data, msg } = res;
      if (code == 0) {
        setBalance(data);
        message.success('查询成功');
      } else {
        message.error(msg);
      }
    });
  };
  const handleSubmit = (values: any) => {
    let { money } = values;
    if (values.operate !== 'transfer' && modifyMoney !== 'plus') {
      money = `-${money}`;
    }
    delete values.modifyMoney;
    cdFinanceOperateAccount({ ...values, ...accountInfo, money }).then((res) => {
      const { code, msg } = res;
      if (code === 0) {
        form1.resetFields();
        form2.resetFields();
        setBalance({ avail_money: '', cash_money: '' });
        setModifyMoney('plus');
        setAccountInfo({});
        form2.setFieldValue('operate', 'transfer');
        form2.setFieldsValue({
          operate: 'transfer',
          account: 'avail_money',
          modifyMoney: 'plus',
        });
        message.success('操作成功');
      } else {
        message.error(msg);
      }
    });
  };
  function selectOptionsMap(data: { [name: string]: string }) {
    if (!data) return [];
    const dMap = Object.keys(data);
    return dMap.map((item) => ({
      label: data[item],
      value: item,
    }));
  }

  useEffect(() => {
    if (kb_type_Value !== 'cdopen') {
      form2?.setFieldValue('operate', 'transfer');
    }
  }, [kb_type_Value]);

  useEffect(() => {
    if (operateValue === 'preOrderCz') {
      form2?.setFieldValue('modifyMoney', 'plus');
      setModifyMoney('plus');
    }
  }, [operateValue]);

  useEffect(() => {
    getUserTypeMap().then((data) => {
      console.log(data, selectOptionsMap(data));
      setUserType(selectOptionsMap(data));
    });
  }, []);

  const getReasonList = debounce(
    (sign: 'add' | 'deduct' | 'transfer' | 'preOrderCz') => {
      cdOperateReasonList({ sign }).then((data) => {
        setOptions(selectOptionsMap(data));
        form2?.setFieldValue('operateReason', null);
      });
    },
    500,
    {
      leading: true,
      trailing: false,
    },
  );

  useEffect(() => {
    if (operateValue) {
      if (operateValue === 'alter') {
        getReasonList(modifyMoney === 'minus' ? 'deduct' : 'add');
      } else {
        getReasonList(operateValue);
      }
    }
  }, [operateValue, modifyMoney]);

  return (
    <>
      <Form
        form={form1}
        {...FormColFormat}
        onFinish={handleSearch}
        initialValues={{
          kb_type: 'cd',
        }}
      >
        <FormItem name='kb_type' label='账号类型'>
          <Select options={userType} placeholder='请选择账号类型' />
        </FormItem>
        <FormItem name='username' label='账号' rules={[{ required: true, message: '请输入账号' }]}>
          <Input placeholder='请输入账号' />
        </FormItem>
        <FormItem label=' ' colon={false}>
          <Button type='primary' htmlType='submit'>
            查询
          </Button>
        </FormItem>
      </Form>
      <Form
        form={form2}
        onFinish={handleSubmit}
        {...FormColFormat}
        initialValues={{
          operate: 'transfer',
          account: 'avail_money',
          modifyMoney,
        }}
      >
        <Title level={5}>查询结果</Title>
        <FormItem label=' ' labelCol={{ span: 1 }} colon={false}>
          <Descriptions column={2}>
            <Descriptions.Item label='可消费'>{balance?.avail_money}</Descriptions.Item>
            <Descriptions.Item label='可提现'>{balance?.cash_money}</Descriptions.Item>
          </Descriptions>
        </FormItem>
        <FormItem name='operate' label='操作选项'>
          <Radio.Group
            options={
              kb_type_Value === 'cdopen'
                ? [...operateOptions, { label: '预充值', value: 'preOrderCz' }]
                : operateOptions
            }
          />
        </FormItem>
        <FormItem name='account' label='操作账户'>
          <Radio.Group options={accountOptions.slice(0, 1)} />
        </FormItem>
        {operateValue === 'transfer' ? (
          <>
            <Title level={5}>目标账户</Title>
            <FormItem name='targetKbType' label='账号类型' initialValue='cd'>
              <Select options={userType} placeholder='请选择账号类型' />
            </FormItem>
            <FormItem name='targetAccount' label='操作账户' initialValue='avail_money'>
              <Radio.Group options={accountOptions.slice(0, 1)} />
            </FormItem>
            <FormItem
              name='money'
              label='转账金额'
              rules={[{ required: true, message: '请输入转账金额' }]}
            >
              <Input placeholder='请输入转账金额' />
            </FormItem>
            <FormItem
              name='targetusername'
              label='目标账号'
              rules={[{ required: true, message: '请输入目标账号' }]}
            >
              <Input placeholder='请输入目标账号' />
            </FormItem>
          </>
        ) : (
          <>
            <FormItem
              name='money'
              label='修改金额'
              rules={[{ required: true, message: '请输入修改金额' }]}
            >
              <Input
                addonBefore={[
                  <FormItem name='modifyMoney' key='modifyMoney' noStyle>
                    <Radio.Group
                      options={
                        operateValue === 'preOrderCz'
                          ? [{ label: '加', value: 'plus' }]
                          : modifyMoneyOptions
                      }
                      onChange={handlemodifyMoney}
                    />
                  </FormItem>,
                ]}
                placeholder='请输入修改金额'
              />
            </FormItem>
          </>
        )}
        <FormItem
          name='phone'
          label='操作者手机号'
          rules={[
            { required: true, message: '请输入操作者手机号' },
            { pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: '请输入正确手机号' },
          ]}
        >
          <Input placeholder='请输入操作者手机号' onChange={changePhone} />
        </FormItem>
        <FormItem name='code' label='验证码' rules={[{ required: true, message: '请输入验证码' }]}>
          <Input
            addonAfter={[
              <KbCaptcha onCheck={onCheck} sendCode={sendCode} queryData={{ phone }} key='code' />,
            ]}
            placeholder='请输入验证码'
          />
        </FormItem>
        <FormItem
          name='dingDingNumber'
          label='申请的钉钉编号'
          rules={[{ required: true, message: '请输入钉钉编号' }]}
        >
          <Input placeholder='请输入钉钉编号' />
        </FormItem>
        <FormItem
          name='operateReason'
          label='操作原因'
          rules={[{ required: true, message: '请选择操作原因' }]}
        >
          <Select options={options} placeholder='请选择操作原因' />
        </FormItem>
        <FormItem
          name='reason'
          label='原因'
          rules={[{ required: true, message: '请输入操作事由' }]}
        >
          <Input.TextArea placeholder='请输入操作事由' />
        </FormItem>
        <FormItem label=' ' colon={false}>
          <Button type='primary' htmlType='submit'>
            确认提交
          </Button>
        </FormItem>
      </Form>
    </>
  );
};

export default Index;
